﻿Imports System.Web
Imports System.Security.Principal

Namespace Seguranca.Servico

    ''' <summary>
    ''' Classe base de autenticação de serviço.
    ''' </summary>
    ''' <remarks></remarks>
    Public MustInherit Class BaseAutenticacaoServico
        Implements IAutenticacaoServico

        Public MustOverride Property CampoSenha() As String Implements IAutenticacaoServico.CampoSenha

        ''' <summary>
        ''' Função que identifica se o usuário já está autenticado no Sistema. 
        ''' </summary>
        ''' <param name="_httpContext">System.Web.HttpContext</param>
        ''' <returns>Boolean</returns>
        ''' <remarks></remarks>
        Public Overridable Function UsuarioEstaAutenticado(ByVal _httpContext As System.Web.HttpContext) As Boolean Implements IAutenticacaoServico.UsuarioEstaAutenticado
            If Not IsNothing(_httpContext) Then
                If (Not _httpContext.User Is Nothing) Then
                    If (_httpContext.User.Identity.IsAuthenticated) Then
                        Return True
                    End If
                End If
            End If
            Return False
        End Function

        ''' <summary>
        ''' Função que obtem o nome do usuário que foi autenticado pelo sistema.
        ''' </summary>
        ''' <returns>String</returns>
        ''' <remarks></remarks>
        Public Function ObtemNomeUsuarioAutenticado() As String Implements IAutenticacaoServico.ObtemNomeUsuarioAutenticado
            If Not IsNothing(HttpContext.Current) Then
                If (Not HttpContext.Current.User Is Nothing) AndAlso _
                           (HttpContext.Current.User.Identity.IsAuthenticated) Then
                    Return HttpContext.Current.User.Identity.Name
                End If
            End If
            Return Nothing
        End Function

        ''' <summary>
        ''' Função que obtém endereço IP do cliente cujo usuário está autenticado.
        ''' </summary>
        ''' <returns>String</returns>
        ''' <remarks></remarks>
        Public Function ObtemIPUsuarioAutenticado() As String Implements IAutenticacaoServico.ObtemIPUsuarioAutenticado
            If Not IsNothing(HttpContext.Current) Then
                If (Not HttpContext.Current.User Is Nothing) AndAlso _
                           (HttpContext.Current.User.Identity.IsAuthenticated) Then
                    Return HttpContext.Current.Request.UserHostAddress
                End If
            End If
            Return Nothing
        End Function

        ''' <summary>
        ''' Função que obtém o valor de chave do Perfil do usuário logado.
        ''' </summary>
        ''' <param name="_chave">String</param>
        ''' <returns>String</returns>
        ''' <remarks></remarks>
        Public Function ObtemPerfilValorPorPerfilChave(ByVal _chave As String) As String _
            Implements IAutenticacaoServico.ObtemPerfilValorPorPerfilChave
            If Not IsNothing(HttpContext.Current) Then
                If (Not HttpContext.Current.Session Is Nothing) Then
                    Dim _perfisUsuario As List(Of Miron.Framework.Seguranca.Dominio.Perfil)
                    If Not IsNothing(HttpContext.Current.Session("_perfisUsuario")) Then
                        _perfisUsuario = CType(HttpContext.Current.Session("_perfisUsuario"),  _
                                               List(Of Miron.Framework.Seguranca.Dominio.Perfil))
                        For Each _perfil As Miron.Framework.Seguranca.Dominio.Perfil In _perfisUsuario
                            If _perfil.Chave = _chave Then
                                Return _perfil.Valor
                            End If
                        Next
                    End If
                End If
            End If
            Return Nothing
        End Function

        ''' <summary>
        ''' Função que obtém o valor de chave da Sessão do usuário logado.
        ''' </summary>
        ''' <param name="_chave">String</param>
        ''' <returns>String</returns>
        ''' <remarks></remarks>
        Public Function ObtemSessaoValorPorSessaoChave(ByVal _chave As String) As String _
            Implements IAutenticacaoServico.ObtemSessaoValorPorSessaoChave
            If Not IsNothing(HttpContext.Current) Then
                If (Not HttpContext.Current.Session Is Nothing) Then
                    If Not IsNothing(HttpContext.Current.Session(_chave)) Then
                        Return HttpContext.Current.Session(_chave)
                    Else
                        Return Nothing
                    End If
                End If
            End If
            Return Nothing
        End Function

        ''' <summary>
        ''' Obtém usuário da sessão e registra-o no contexto http
        ''' </summary>
        ''' <param name="_httpContext">System.Web.HttpContext</param>
        ''' <returns>Boolean</returns>
        ''' <remarks></remarks>
        Public Function RecuperaContextoUsuario(ByVal _httpContext As System.Web.HttpContext) As Boolean Implements IAutenticacaoServico.RecuperaContextoUsuario
            Dim _sessao As SessionState.HttpSessionState = _httpContext.Session
            If Not _sessao Is Nothing Then
                Dim _principal As IPrincipal = TryCast(_sessao("Usuario"), IPrincipal)
                _httpContext.User = _principal
            End If
        End Function

        ''' <summary>
        ''' Obtém usuário do contexto http e persiste-o na sessão.
        ''' </summary>
        ''' <param name="_httpContext">System.Web.HttpContext</param>
        ''' <returns>Boolean</returns>
        ''' <remarks></remarks>
        Public Function PersisteContextoUsuario(ByVal _httpContext As System.Web.HttpContext) As Boolean Implements IAutenticacaoServico.PersisteContextoUsuario
            Dim _sessao As SessionState.HttpSessionState = _httpContext.Session
            Dim _principal As IPrincipal = Nothing
            If Not _sessao Is Nothing Then
                _principal = _httpContext.User
                _sessao("Usuario") = _principal
            End If
            Threading.Thread.CurrentPrincipal = _principal
        End Function

        ''' <summary>
        ''' Função de autenticação do usuário
        ''' </summary>
        ''' <param name="_nomeUsuario">String</param>
        ''' <param name="_senha">String</param>
        ''' <returns>classe Dominio.Usuario</returns>
        ''' <remarks></remarks>
        Public Overridable Function AutenticaUsuario(ByVal _nomeUsuario As String, ByVal _senha As String) As Dominio.Usuario Implements IAutenticacaoServico.AutenticaUsuario
            Return Nothing
        End Function

        Public Overridable Function UsuarioEstaBloqueado(ByVal _nomeUsuario As String) As Boolean _
            Implements IAutenticacaoServico.UsuarioEstaBloqueado
            Return False
        End Function

        '''' <summary>
        '''' Alteração de senha do usuário
        '''' </summary>
        '''' <param name="_login">String</param>
        '''' <param name="_senha">String</param>
        '''' <remarks></remarks>
        'Public Overridable Sub AlterarSenha(ByVal _login As String, ByVal _senha As String) _
        '    Implements IAutenticacaoServico.AlterarSenha
        '    Throw New NotImplementedException
        'End Sub


        MustOverride Function GerarSenhaForte() As String Implements IAutenticacaoServico.GerarSenhaForte

        MustOverride Function RetornarNotaSenha(ByVal _senha As String) As Integer Implements IAutenticacaoServico.RetornarNotaSenha

        MustOverride Function SenhaEhForte(ByVal _senha As String) As Boolean Implements IAutenticacaoServico.SenhaEhForte

        MustOverride Sub AlterarSenha(ByVal _login As String, ByVal _senhaAtual As String, ByVal _novaSenha As String, Optional ByVal _confirmacaoNovaSenha As String = "") Implements IAutenticacaoServico.AlterarSenha

        MustOverride Function Autentica(ByVal _login As String, ByVal _senha As String) As ResultadoAutenticacao Implements IAutenticacaoServico.Autentica

        MustOverride Sub AlterarDataExpiracaoSenha(ByVal _login As String, ByVal _novaData As Date) Implements IAutenticacaoServico.AlterarDataExpiracaoSenha

    End Class

End Namespace
